import 'dart:convert';

import 'package:aqua_plunge/controller/UserController.dart';
import 'package:aqua_plunge/http/Url.dart';
import 'package:aqua_plunge/page/login_page.dart';
import 'package:aqua_plunge/page/tab_navigation_page.dart';
import 'package:flutter_util_code/device_utils.dart';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;

import '../http/app_manager.dart';
import '../util/header_util.dart';

class LoginDao {
  static Utf8Decoder utf8decoder = const Utf8Decoder();
  static UserController _userController = Get.find<UserController>();

  ///快速登录
  static Future fastLogin(Function?  success,Function? fail) async {
    var httpurl = Uri.parse(AppUrl.login);
    String devid = await DeviceUtils.getDeviceId();
    Map<String, String> bodyParams = {};
    bodyParams['oauthType'] = "4";
    bodyParams['token'] = devid;
    try {
      var response = await http.post(httpurl,
          headers: await HeaderUtil().getHeader(login: true),
          body: Uri(queryParameters: bodyParams).query,
          encoding: const Utf8Codec());
      if (response.statusCode == 200 && success!= null) {
        var result = json.decode(utf8decoder.convert(response.bodyBytes));
        if(result['data'] != null && result['data']['token'] !=null){
          AppManager.saveToken(result['data']['token']);
          AppManager.setUserInfo(json.encode(result['data']['userInfo']));
          _userController.fetchUserData();
          success();
        }else if(fail != null){
          fail("${result['msg']}");
        }
      } else {
        throw Exception('"Request failed with status: ${response.statusCode}"');
      }
    } catch (e) {
      Future.error(e);
    }
  }


  ///苹果登录
  static Future appleLogin(String identityToken,Function? success) async {

    var httpurl = Uri.parse(AppUrl.login);
    Map<String, String> bodyParams = {};
    bodyParams['oauthType'] = "3";
    bodyParams['token'] = identityToken;
    try {
      var response = await http.post(httpurl,
          headers: await HeaderUtil().getHeader(login: true),
          body: Uri(queryParameters: bodyParams).query,
          encoding: const Utf8Codec());
      if (response.statusCode == 200 && success != null) {
        var result = json.decode(utf8decoder.convert(response.bodyBytes));
        if(result['data']['token'] != null){
          AppManager.saveToken(result['data']['token']);
          AppManager.setUserInfo(json.encode(result['data']['userInfo']));
          _userController.fetchUserData();
          success();
        }
      } else {
        throw Exception('"Request failed with status: ${response.statusCode}"');
      }
    } catch (e) {
      Future.error(e);
    }
  }

  ///Token检验
  static Future<bool> checkToken(String tokenStr) async {
    var httpurl = Uri.parse(AppUrl.validToken);
    final bodyParams = {"token": tokenStr};
    final jsonStr = json.encode(bodyParams);
    try {
      var response = await http.post(httpurl,
          headers: await HeaderUtil().getHeader(),
          body: jsonStr,
          encoding: const Utf8Codec());
      if (response.statusCode == 200) {
        var result = json.decode(utf8decoder.convert(response.bodyBytes));
        if (result['success'] == true && result['data'] == true) {
          return true;
        }else{
          return false;
        }
      } else {
        throw Exception('"Request failed with status: ${response.statusCode}"');
      }
    } catch (error) {
      Future.error(error);
    }
    return false;
  }

  ///退出登录
  static Future<void> logout() async {
    var httpurl = Uri.parse(AppUrl.logout);
    try {
      var response = await http.post(httpurl,
          headers: await HeaderUtil().getHeader(), encoding: const Utf8Codec());
      if (response.statusCode == 200) {
        var result = json.decode(utf8decoder.convert(response.bodyBytes));
        if(result['data'] != null){
          Get.offAll(const LoginPage());
        }
      } else {
        throw Exception('"Request failed with status: ${response.statusCode}"');
      }
    } catch (error) {
      Future.error(error);
    }
  }

  ///删除账号
  static Future<void> deleteAccount(Function? success) async {
    var httpurl = Uri.parse(AppUrl.deleteAccout);
    try {
      var response = await http.post(httpurl,
          headers: await HeaderUtil().getHeader(), encoding: const Utf8Codec());
      if (response.statusCode == 200 && success!=null) {
        var result = json.decode(utf8decoder.convert(response.bodyBytes));
        if(result['data'] != null){
          success();
        }
      } else {
        throw Exception('"Request failed with status: ${response.statusCode}"');
      }
    } catch (error) {
      Future.error(error);
    }
  }

}
